package com.capgemini.task;

import java.lang.reflect.Method;
import java.util.Date;

import com.capgemini.base.support.spring.SpringUtils;
import com.capgemini.task.domain.ScheduleJob;
import com.capgemini.task.domain.ScheduleJobRunLog;
import com.capgemini.task.service.SaveLogThread;
import org.apache.commons.lang.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskUtils {
	private final static Logger log = LoggerFactory.getLogger(TaskUtils.class);

	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleJob
	 */
	public static void invokMethod(ScheduleJob scheduleJob) {
		ScheduleJobRunLog scheduleJobRunLog = new ScheduleJobRunLog();
		scheduleJobRunLog.setSuccessFlag(true);
		scheduleJobRunLog.setDescp("success");
		Date beginTime = new Date();
		scheduleJobRunLog.setBeginTime(beginTime);

		Object object = null;
		Class clazz;
		if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
			object = SpringUtils.getBean(scheduleJob.getSpringId());
		} else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
			try {
				clazz = Class.forName(scheduleJob.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				log.error("", e);
				scheduleJobRunLog.setSuccessFlag(false);
				scheduleJobRunLog.setDescp(e.getMessage());
			}

		}
		if (object == null) {
			log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，请检查是否配置正确！！！");

			scheduleJobRunLog.setSuccessFlag(false);
			scheduleJobRunLog.setDescp("任务名称 = [" + scheduleJob.getJobName() + "]----未启动成功，请检查是否配置正确！！！");

		}else {
			clazz = object.getClass();
			Method method = null;
			try {
				method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
			} catch (NoSuchMethodException e) {
				log.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，方法名设置错误！！！");
				log.error("", e);
				scheduleJobRunLog.setSuccessFlag(false);
				scheduleJobRunLog.setDescp("任务名称 = [" + scheduleJob.getJobName() + "]，方法名设置错误！！！");
			} catch (Exception e) {
				log.error("", e);
				scheduleJobRunLog.setSuccessFlag(false);
				scheduleJobRunLog.setDescp(e.getMessage());
			}
			if (method != null) {
				try {
					log.info("任务名称 = [" + scheduleJob.getJobName() + "]---------开始执行");
					method.invoke(object);
				} catch (Exception e) {
					log.error("", e);
					scheduleJobRunLog.setSuccessFlag(false);
					scheduleJobRunLog.setDescp(e.getMessage());
				}
			}
		}
		log.info("任务名称 = [" + scheduleJob.getJobName() + "]----------执行结束");
		Date endTime = new Date();
		scheduleJobRunLog.setEndTime(endTime);

		scheduleJobRunLog.setJobId(scheduleJob.getJobId());

		new SaveLogThread(scheduleJobRunLog).start();

	}
}
